const { body } = require('express-validator')
const validate = require('../middleware/validator')
const User = require('../models/index/User')
const md5 = require('../util/md5')

exports.register = validate([
  body('username')
    .notEmpty()
    .withMessage('用户名不能为空')
    .custom(async (username) => {
      const user = await User.findOne({
        where: {
          username
        }
      })
      if (user) {
        return Promise.reject('用户名已经存在')
      }
    }),
  body('password').notEmpty().withMessage('密码不能为空')
])

// 先验证再查询数据库
exports.login = [
  validate([
    body('username').notEmpty().withMessage('用户名不能为空'),
    body('password').notEmpty().withMessage('密码不能为空')
  ]),
  validate([
    body('username').custom(async (username, { req }) => {
      const user = await User.findOne({
        where: {
          username
        }
      })
      if (!user) {
        return Promise.reject('用户不存在')
      }
      req.user = user
    })
  ]),
  validate([
    body('password').custom(async (password, { req }) => {
      if (md5(password) !== req.user.password) {
        return Promise.reject('密码错误')
      }
    })
  ])
]
